package org.casper.netty.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {
	
	public void connect(String host,int port) throws Exception{
		//配置客户端的NIO线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			//netty启动NIO的辅助类，配置如如下参数  NIO线程组  Channel类型  TCP连接参数 网络IO事件的处理类
			Bootstrap b = new Bootstrap();				
			b.group(group)										//设置NIO线程组
			.channel(NioSocketChannel.class)					//设置为客户端的socket
			.option(ChannelOption.TCP_NODELAY, true)			//设置TCP的连接参数
			.handler(new ChannelInitializer<SocketChannel>() {	//设置网络IO事件的处理类
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new TimeClientHandler());
				}
			});
			
			//发起 异步连接操作  connect server
			ChannelFuture f = b.connect(host,port).sync();
			
			//等待客户端链路关闭
			f.channel().closeFuture().sync();
		} finally {
			//优雅的释放资源。只是释放相关的资源
			group.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8080;
		if(args !=null && args.length >0){
			try {
				port = Integer.valueOf(args[0]);
			} catch (NumberFormatException e) {
			}
		}
		new TimeClient().connect("127.0.0.1", port);
	}
}
